package com.qiyeji.real_estate.controller;

import com.qiyeji.real_estate.entity.project;
import com.qiyeji.real_estate.entity.projectPhase;
import com.qiyeji.real_estate.entity.staff;
import com.qiyeji.real_estate.entity.workKey;
import com.qiyeji.real_estate.service.ProjectPhaseService;
import com.qiyeji.real_estate.service.ProjectService;
import com.qiyeji.real_estate.service.StaffService;
import com.qiyeji.real_estate.service.WorkService;
import com.qiyeji.real_estate.utils.Result;
import jdk.nashorn.internal.parser.DateParser;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/Project")
@RestController
public class ProjectController {
    @Autowired
    ProjectService projectService;

    @Autowired
    ProjectPhaseService projectPhaseService;

    @Autowired
    StaffService staffService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    HistoryService historyService;

    @Autowired
    WorkService workService;

    @PostMapping("/All_Project")
    public Result getAllProject() {
        List<project> res = projectService.getAllProject();

        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }

    @PostMapping("/QueryProjectByPCode")
    public Result queryProjectByPCode(@RequestBody Map<String, String> params){
        project res = projectService.queryProjectByPCode(params.get("pCode"));

        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }


    @PostMapping("/Get_ProjectByCID")
    public Result getProjectByCID(@RequestBody Map<String, String> params) {
        List<project> res = projectService.getProjectByCID(params.get("cID"));

        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }

    @PostMapping("/Get_ProjectBySCode")
    public Result getProjectBySCode(@RequestBody Map<String, String> params) {
        List<project> res = projectService.getProjectBySCode(params.get("sCode"));

        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }

    @PostMapping("/Get_ProjectByDate")
    public Result getProjectByDate(@RequestBody Map<String, String> params){
        List<project> res = projectService.getProjectByDate('%' + params.get("buildTime") + '%');

        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }

    @PostMapping("/Get_ProjectByName")
    public Result getProjectByName(@RequestBody Map<String, String> params) {
        List<project> res = projectService.getProjectByName( '%' + params.get("pName") + '%');

        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }

    @PostMapping("/AddProject")
    public Result addProject(@RequestBody Map<String, String> params) throws ParseException {
//        java.text.SimpleDateFormat formatter =  new SimpleDateFormat(  "yyyy-MM-dd" );
        String modelManager = params.get("modelCharge");
        String renderManager = params.get("renderCharge");
        String lateManager = params.get("laterCharge");
        staff modelCharge = staffService.queryStaff(modelManager);
        staff renderCharge = staffService.queryStaff(renderManager);
        staff lateCharge = staffService.queryStaff(lateManager);
        project temp = new project(
                params.get("pCode"),
                params.get("cID"),
                params.get("pName"),
                modelCharge.getSname(),
                renderCharge.getSname(),
                lateCharge.getSname(),
                params.get("buildTime"),
                params.get("endTime"),
                params.get("price"),
                params.get("pState")
        );
        System.out.println(temp);
        project project = projectService.queryProjectByPCode(params.get("pCode"));
        if (project == null) {
            Map<String, Object> map = new HashMap<>();
            map.put("modelManager", modelManager);
            map.put("renderManager", renderManager);
            map.put("lateManager", lateManager);
            ProcessInstance simpleTest = runtimeService.startProcessInstanceByKey("ProjectWorkFlow", temp.getPcode(), map);
            System.out.println("流程实例的ProcessInstanceId: " + simpleTest.getId());
            System.out.println("流程实例的ProcessDefinitionId: " + simpleTest.getProcessDefinitionId());
            System.out.println("流程实例的BusinessKey：" + simpleTest.getBusinessKey());
            System.out.println("————————————————————————————————————————————————————");
            Integer res = projectService.addProject(temp);
            workService.insert(new workKey(params.get("pCode"), modelManager, params.get("buildTime")));
            workService.insert(new workKey(params.get("pCode"), renderManager, params.get("buildTime")));
            workService.insert(new workKey(params.get("pCode"), lateManager, params.get("buildTime")));
            projectPhaseService.insert(new projectPhase(temp.getPcode(), "建模", "正在进行"));
            projectPhaseService.insert(new projectPhase(temp.getPcode(), "渲染", "就绪"));
            projectPhaseService.insert(new projectPhase(temp.getPcode(), "后期", "就绪"));
            if (res == null)
                return Result.error();
            else
                return Result.success(res);
        }
        else
            return Result.existPCode();
    }

    @PostMapping("/DeleteProject")
    public Result deleteProject(@RequestBody Map<String, String> params) {
        String pCode = params.get("pCode");
        Integer res = projectService.deleteProject(pCode);
        List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(pCode).list();
        if (processInstances != null) {
            for (ProcessInstance processInstance: processInstances){
                runtimeService.deleteProcessInstance(processInstance.getId(), "删除项目");
                historyService.deleteHistoricProcessInstance(processInstance.getId());
            }
        }else {
            List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(pCode).list();
            if (historicProcessInstances != null)
                for (HistoricProcessInstance historicProcessInstance: historicProcessInstances){
                    historyService.deleteHistoricProcessInstance(historicProcessInstance.getId());
                }
        }
        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }

    @PostMapping("/AlterProject")
    public Result alterProject(@RequestBody Map<String, String> params) throws ParseException {
//        java.text.SimpleDateFormat formatter =  new SimpleDateFormat(  "yyyy-MM-dd" );
        Integer res = projectService.alterProject(new project(
                params.get("pCode"),
                params.get("cID"),
                params.get("pName"),
                params.get("modelCharge"),
                params.get("renderCharge"),
                params.get("laterCharge"),
                params.get("buildTime"),
                params.get("endTime"),
                params.get("price"),
                params.get("pState")
        ));

        if (res == null)
            return Result.error();
        else
            return Result.success(res);
    }

    @PostMapping("/GetProjectBysCode")
    public Result getProjectBysCode(@RequestBody Map<String ,String> params) {
        List<project> res = projectService.getProjectBysCode(params.get("sCode"));

        if (res == null)
            return Result.error("无任何记录！");
        else
            return Result.success(res);
    }

}
